package com.example.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.Service.RawMaterialService;
import com.example.Service.XsOrderService;
import com.example.dao.RawMaterialMapper;
import com.example.dao.XSOrderMapper;
import com.example.dao.XScustomentMapper;
import com.example.exception.MyException;
import com.example.pojo.RawMaterial;
import com.example.pojo.XsCustomer;
import com.example.pojo.XsOrder;
import com.example.util.Result;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/xsorder")
@Api(tags = "订单信息")
public class XsOrderController {
    @Resource
    private XsOrderService xsOrderService;

    @Resource
    private RawMaterialService rawMaterialService;
    @Resource
    private XSOrderMapper xsOrderMapper;
    @Resource
    private RawMaterialMapper rawMaterialMapper;
    @Resource
    private XScustomentMapper xScustomentMapper;
    //查询订单
    @PostMapping("/selectAllByState")
    public Object selectAllByState(String state) {
        QueryWrapper<XsOrder> queryWrapper = new QueryWrapper<>();
        if (!state.equals("审批后")){
            queryWrapper.eq("approval_status", state);
        }else {
            queryWrapper.in("approval_status","已通过","已拒绝");
        }
        queryWrapper.orderByAsc("update_time");
        List<XsOrder> xsOrders =xsOrderMapper.selectList(queryWrapper);
        for (XsOrder xsOrder : xsOrders) {
            QueryWrapper<RawMaterial> rawMaterialQueryWrapper = new QueryWrapper<>();
            rawMaterialQueryWrapper.eq("id",xsOrder.getMaTid());
            RawMaterial rawMaterial =rawMaterialMapper.selectOne(rawMaterialQueryWrapper);
            xsOrder.setName(rawMaterial.getName());
            QueryWrapper<XsCustomer> xsCustomerQueryWrapper = new QueryWrapper<>();
            xsCustomerQueryWrapper.eq("customer_id",xsOrder.getCuid());
            XsCustomer xsCustomer=xScustomentMapper.selectOne(xsCustomerQueryWrapper);
            xsOrder.setCustomerName(xsCustomer.getCustomerName());
        }
        return new Result("200", "查询订单", xsOrders);
    }
    //查看数量
    @PostMapping("/selectXSCountByState")
    public Object selectXSCountByState(String state) {
        QueryWrapper<XsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("approval_status", state);
        queryWrapper.groupBy("approval_status");
        queryWrapper.select(new String[]{"approval_status", "COUNT(*) as count"}); // 修正为数组形式
        return new Result("200", "查询", xsOrderMapper.selectList(queryWrapper));
    }
    //根据id审批
    @PostMapping("/updateXSByState")
    private Object updateXSByState(@RequestBody XsOrder xsOrder){
        xsOrderMapper.updateById(xsOrder);
        return new Result("200","修改成功");
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //             楚河·汉界
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//    根据客户id/商品id/订单id查询订单信息
    @GetMapping("/getList")
    public Object getList(
            @RequestParam(value = "cuid",defaultValue = "") Integer cuid,
            @RequestParam(value = "id",defaultValue = "") Integer id,
            @RequestParam(value = "maTid",defaultValue = "") Integer maTid,
            @RequestParam(value = "PageNum",defaultValue = "1") int PageNum,
            @RequestParam(value = "PageSize",defaultValue = "5") int PageSize
    ){
        HashMap<String,Object> map=new HashMap<>();
        Page<XsOrder> page = new Page<>(PageNum,PageSize);
        IPage<XsOrder> xsOrderIPage = xsOrderService.joinQuery(page,cuid,id,maTid);
        map.put("total",xsOrderIPage.getTotal());
        map.put("rows",xsOrderIPage.getRecords());
        map.put("pages",xsOrderIPage.getPages());
        return new Result<>("200","查询成功",map);
    }



    // 添加销售订单
    @SuppressWarnings("DuplicatedCode")
    @PostMapping("/add")
    public Object add(@RequestBody XsOrder xsOrder){
        // 验证非空
        if (xsOrder==null){
            throw new MyException("456","客户信息不能为空");
        }
        // 根据商品id查询商品信息
        QueryWrapper<RawMaterial>
                queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("id",xsOrder.getMaTid());
        RawMaterial rawMaterial = rawMaterialService.getOne(queryWrapper);
        //是否有此商品
        if (rawMaterial==null){
            throw new MyException("457","商品信息不存在");
        }
        // 检查库存是否充足
        Integer stock = rawMaterial.getNumber();
        if (stock<xsOrder.getOrderQuantity()){
            throw new MyException("458","商品库存不足");
        }
        // 扣减库存
        rawMaterial.setNumber(stock-xsOrder.getOrderQuantity());
        if(!rawMaterialService.updateById(rawMaterial)){
            throw new MyException("458","扣减库存失败");
        }
        // 计算订单金额
        xsOrder.setOrderAmount(rawMaterial.getPrice()*xsOrder.getOrderQuantity());
        // 保存销售订单
        if (!xsOrderService.save(xsOrder)){
            throw new MyException("459","添加订单信息失败");
        }
        return new Result<>("200","添加订单信息成功");
    }


    // 订单审批
    @PostMapping("/updateStatus")
    public Object updateStatus(
            @RequestParam("id") Integer id,
            @RequestParam("approvalStatus") String approvalStatus,
            @RequestParam("comment") String comment
    ){
        //查询订单
        QueryWrapper<XsOrder>
                queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        XsOrder xsOrder = xsOrderService.getOne(queryWrapper);
        // 判断订单是否存在
        if (xsOrder==null){
            throw new MyException("457","订单信息不存在");
        }
        // 判断订单是否已存档
        if (xsOrder.getDeleted()==1) {
            throw new MyException("456","订单已存档");
        }
        //判断审批过程中是否写批注
        if (comment!=null||!comment.equals("")){
            xsOrder.setComment(comment);
        }
        //根据商品id查询商品信息
        QueryWrapper<RawMaterial>
                queryWrapper2= new QueryWrapper<>();
        queryWrapper2.eq("id",xsOrder.getMaTid());
        RawMaterial rawMaterial = rawMaterialService.getOne(queryWrapper2);
        //是否有此商品
        if (rawMaterial==null){
            throw new MyException("457","商品信息不存在");
        }
        //未通过则返回“审核成功，未通过”
        if (approvalStatus.equals("已拒绝")){
            xsOrder.setDeleted(1);
            xsOrder.setApprovalStatus("已拒绝");
            xsOrderService.updateById(xsOrder);
            rawMaterial.setNumber(rawMaterial.getNumber()+xsOrder.getOrderQuantity());
            rawMaterialService.updateById(rawMaterial);
            return new Result<>("200","审核完成，未通过");
        }
        // 检查库存是否充足
        System.out.println(rawMaterial.getNumber());
        Integer stock = rawMaterial.getNumber();
        if (stock<xsOrder.getOrderQuantity()){
            throw new MyException("458","商品库存不足");
        }
        // 扣减库存
        rawMaterial.setNumber(stock-xsOrder.getOrderQuantity());
        if(!rawMaterialService.updateById(rawMaterial)){
            throw new MyException("458","扣减库存失败");
        }
        // 修改订单状态
        if (approvalStatus.equals("已通过")){
            xsOrder.setApprovalStatus(approvalStatus);
        }
        if (!xsOrderService.updateById(xsOrder)){
            throw new MyException("458","修改订单状态失败");
        }
        return new Result<>("200","修改订单状态成功，已通过审核",null);
    }



//    订单的发货收款
    @PostMapping("/updateShipmentStatus")
    public Object updateShipmentStatus(@RequestBody XsOrder xsOrder){
//        判断订单是否通过审核
        if (!xsOrder.getApprovalStatus().equals("已通过")){
            throw new MyException("457","订单未通过审核");
        }
//        判断订单是否发货
        if (!xsOrder.getShipmentStatus().equals("未发货")){
            throw new MyException("457","订单不合规");
        }
//       订单发货
        xsOrder.setShipmentStatus("已发货");
        xsOrder.setReceivedAmount("是");
//        修改订单状态
        if (!xsOrderService.updateById(xsOrder)){
            throw new MyException("458","修改订单状态失败");
        }
        return new Result<>("200","订单已经发货成功");
    }


//    根据id查询订单,并且把此订单中商品的库存，存到商品库里
    @PostMapping("/getById")
    public Object getById(@RequestBody XsOrder xsOrder){
        //根据商品id查询商品信息
        QueryWrapper<RawMaterial>
                queryWrapper2= new QueryWrapper<>();
        queryWrapper2.eq("id",xsOrder.getMaTid());
        RawMaterial rawMaterial = rawMaterialService.getOne(queryWrapper2);
        //是否有此商品
        if (rawMaterial==null){
            throw new MyException("457","商品信息不存在");
        }
        rawMaterial.setNumber(rawMaterial.getNumber()+xsOrder.getOrderQuantity());
        xsOrder.setOrderQuantity(0);
        xsOrder.setOrderAmount(0.0);
        rawMaterialService.updateById(rawMaterial);
        xsOrderService.updateById(xsOrder);
        return new Result<>("200","订单");
    }



//    修改销售订单
    @PostMapping("/update")
    public Object update(@RequestBody XsOrder xsOrder){
        // 判断订单是否通过审核
        if (xsOrder.getApprovalStatus().equals("已通过")){
            return new Result<>("457","订单已通过审核，无法修改");
        }
        // 根据商品id查询商品信息
        QueryWrapper<RawMaterial>
                queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",xsOrder.getMaTid());
        RawMaterial rawMaterial = rawMaterialService.getOne(queryWrapper);
        System.out.println(rawMaterial);
        if (rawMaterial==null){
            throw new MyException("457","商品信息不存在");
        }
        // 检查库存是否充足
//        System.out.println(rawMaterial.getNumber());
        Integer stock = rawMaterial.getNumber();
        if (stock<xsOrder.getOrderQuantity()){
            throw new MyException("458","商品库存不足");
        }
        // 扣减库存
        rawMaterial.setNumber(stock-xsOrder.getOrderQuantity());
        if(!rawMaterialService.updateById(rawMaterial)){
            throw new MyException("458","扣减库存失败");
        }
        // 计算订单金额
        xsOrder.setOrderAmount(rawMaterial.getPrice()*xsOrder.getOrderQuantity());
        // 保存修改的销售订单
        if(!xsOrderService.updateById(xsOrder)){
            throw new MyException("459","修改客户信息失败");
        }
        return new Result<>("200","修改客户信息成功");
    }

//    删除销售订单
    @DeleteMapping("/delete")
    public Result delete(@RequestParam("id") Integer id){
//        逻辑删除
        if (!xsOrderService.removeById(id)){
            throw new MyException("460","删除客户信息失败");
        }
        return new Result<>("200","删除客户信息成功");
    }







}
